local Bartender4 = _G.Bartender4
assert(Bartender4, "Bartender4 not found")

local mod = LibStub("AceAddon-3.0"):NewAddon("Bartender4_Dualspec", "AceEvent-3.0")

local db
local defaults = {
	profile = {},
}

function mod:OnInitialize()
	db = LibStub("AceDB-3.0"):New("Bartender4DualspecDB", defaults)
	mod:MakeOptions()
end

local current_talents

function mod:OnEnable()
	current_talents = GetActiveTalentGroup()
	mod:RegisterEvent("PLAYER_TALENT_UPDATE")
	if not (current_talents == 1 and 
						Bartender4.db:GetCurrentProfile() == db.profile.primary)
			and not (current_talents == 2 and 
								Bartender4.db:GetCurrentProfile() == db.profile.secondary) then
		current_talents = nil
		mod:PLAYER_TALENT_UPDATE()
	end
end

function mod:PLAYER_TALENT_UPDATE()
	local new_talents = GetActiveTalentGroup()
	if new_talents ~= current_talents then
		if db.profile.enabled then
			if new_talents == 1 and db.profile.primary then
				Bartender4.db:SetProfile(db.profile.primary)
			elseif new_talents == 2 and db.profile.primary then
				Bartender4.db:SetProfile(db.profile.secondary)
			else
				assert(false, "active talentspec is neither 1 nor 2")
			end
		end
		current_talents = new_talents
	end
end

local function setOption(info, value)
	db.profile[info[#info - 1]] = value
end

local choices = {}

local function getProfileChoices()
	wipe(choices)
	for _, v in pairs(Bartender4.db:GetProfiles()) do
		choices[v] = v
	end
	return choices
end

local options = {
	name = "Bartender4 - Dualspec",
	desc = "Bartender4 - Dualspec",
	type = 'group',
	args = {
		enabled = {
			name = "Enabled",
			desc = "Enable dualspec profile changing",
			type = 'toggle',
			get = function() return not not db.profile.enabled end,
			set = function(info, value) db.profile.enabled = value end,
		},
		primary = {
			name = "Primary",
			desc = "Profile for Primary Talent spec",
			type = 'select',
			values = getProfileChoices,
			get = function() return db.profile.primary end,
			set = function(info, value) db.profile.primary = value end,
			disabled = function() return not db.profile.enabled == true end,
		},
		secondary = {
			name = "Secondary",
			desc = "Profile for Secondary Talent spec",
			type = 'select',
			values = getProfileChoices,
			get = function() return db.profile.secondary end,
			set = function(info, value) db.profile.secondary = value end,
			disabled = function() return not db.profile.enabled == true end,
		},
	},
}

local AceConfig = LibStub("AceConfig-3.0")
local AceConfigDialog = LibStub("AceConfigDialog-3.0")

function mod:MakeOptions()
	AceConfig:RegisterOptionsTable("Bartender4_Dualspec", options)
	AceConfigDialog:AddToBlizOptions("Bartender4_Dualspec", "Bartender4_Dualspec")
end
